package Arrays;

/**
 * 作者:hfj
 * 功能:13.罗马数字转整数
 * 日期: 2025/10/16 21:08
 */
public class RomanToInt {
    public static void main(String[] args) {
        String s = "MCMXCIV";
        System.out.println(romanToInt(s));
    }

    public static int romanToInt(String s) {
        int lens = s.length();
        int temp = 0,result = 0;
        int[] nums = new int[lens]; //创建一个数组用来存取
        //取出罗马数字中字符对应的数值并放入数组当中
        for (int i = 0; i < s.length(); i++) {
            switch (s.charAt(i)){
                case 'I':
                    temp = 1;
                    break;
                case 'V':
                    temp = 5;
                    break;
                case 'X':
                    temp = 10;
                    break;
                case 'L':
                    temp = 50;
                    break;
                case 'C':
                    temp = 100;
                    break;
                case 'D':
                    temp = 500;
                    break;
                case 'M':
                    temp = 1000;
                    break;
            }
            nums[i] = temp;
        }

        //如果左边的数字小于右边的数字，则相减，否则相加即可
        for (int i = 0; i < nums.length; i++) {
            if (i < nums.length-1 && nums[i] < nums[i+1]){
                result -=nums[i];
            }else{
                result +=nums[i];
            }
        }
        return result;
    }
}
